<template>
  <ele-modal
    form
    width="95%"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        highlight-current-row
        v-model:selections="selections"
        border
        stripe
        row-key="id"
        row-click-checked
      >
        <template #toolbar="{}">
          <el-button
            v-if="props.action == 'pay'"
            type="primary"
            @click="toPay()"
          >
            提交至下一步
          </el-button>
        </template>
        <template #cash="{ row }">
          <el-checkbox v-model="row.cash" />
        </template>
        <template #rebate="{ row }">
          <el-input v-model="row.rebate" />
          <!-- <span>{{ row.rebate }}</span> -->
        </template>
        <template #insurance="{ row }">
          <!-- <el-select
            v-if="row.cate !== '交强险' && row.cate !== '商业险'"
            v-model="row.insurance_id"
            placeholder="请选择报价的保险公司"
            filterable
            @change="handleInsuranceChange(row)"
          >
            <el-option label="请选择" :value="0">请选择</el-option>
            <el-option
              v-for="(item, index) in insuranceList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              @click="setInsurance(index, row)"
            >
              {{ item.title }}
            </el-option>
          </el-select> -->
          <span>{{ row.insurance }}</span>
        </template>
        <template #insurance_salesman="{ row }">
          <!-- <span
            v-if="row.cate !== '交强险' && row.cate !== '商业险'"
            class="blue pointer"
            @click="openSalesman(row)"
          >
            {{ row.insurance_salesman || '请选择' }}
          </span> -->
          <span>{{ row.insurance_salesman }}</span>
        </template>
        <template #totalPrice="{ row }">
          <span :class="priceClass(row.raise_price)">{{ row.totalPrice }}</span>
        </template>

        <template #otherPrice="{ row }">
          {{ row.otherPrice }}
        </template>
        <template #s_time="{ row }">
          <el-date-picker
            v-model="row.s_time_date"
            type="date"
            placeholder="结束日期"
            style="width: 120px"
            value-format="YYYY-MM-DD"
            :clearable="false"
          />
          <el-input
            v-model.number="row.s_time_h"
            class="ml3"
            style="width: 73px"
          >
            <template #append>时</template>
          </el-input>
        </template>
        <template #e_time="{ row }">
          <el-date-picker
            v-model="row.e_time_date"
            type="date"
            placeholder="结束日期"
            style="width: 120px"
            value-format="YYYY-MM-DD"
            :clearable="false"
          />
          <el-input
            v-model.number="row.e_time_h"
            class="ml3"
            style="width: 73px"
          >
            <template #append>时</template>
          </el-input>
        </template>
        <template #pdf="{ row }">
          <file
            botton-text="上传"
            botton-size="small"
            botton-type="success"
            style="margin-top: 10px; margin-right: 8px"
            @done="onUpladDone($event, row)"
          />
          <span
            v-if="row.pdf !== ''"
            @click="openPdf(row.pdf)"
            class="blue pointer"
            >查看</span
          >
        </template>
        <template #payQrcode="{ row }">
          <file
            botton-text="上传"
            botton-size="small"
            botton-type="success"
            style="margin-top: 10px; margin-right: 8px"
            @done="onQrUpladDone($event, row)"
          />
          <span
            v-if="row.pay_qrcode !== ''"
            @click="openImages(row, 'qrcode')"
            class="blue pointer"
            >查看</span
          >
        </template>
        <template #img="{ row }">
          <span
            v-if="row.images !== ''"
            class="pointer blue"
            @click="openImages(row, 'offer')"
            >查看</span
          >
          <span v-else>无</span>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 报价 -->
    <offer-b-detail v-model="showDetail" :offer-id="offerId" />
    <!-- 图片 -->
    <images v-model="showImages" :data="current" :image-type="imageType" />
    <!-- 业务员 -->
    <salesman
      v-model="showSalesman"
      :company-id="companyId"
      @done="salesmanDone"
      action="choose"
    />
  </ele-modal>
</template>

<script setup>
  import { ref, watch, computed } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { ElMessageBox } from 'element-plus/es';
  import {
    pageWatingBuyInsurance,
    updateInsurancePdf,
    setTradeToPay,
    updateInsuranceOfferQr
  } from '@/api/company';
  const emit = defineEmits(['done', 'update:modelValue']);
  import OfferBDetail from '@/views/insurance/components/offer-b-detail.vue';
  import Images from './offer-images.vue';
  import Salesman from '@/views/system/insurance/salesman/index.vue';
  import file from '@/components/FileUpload/file.vue';

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    data: Object,
    action: {
      type: String,
      default: 'pay'
    }
  });
  const title = ref('');
  /** 表格实例 */
  const tableRef = ref(null);

  const priceClass = (value) => {
    return value > 0 ? 'red' : 'blue';
  };

  const current = ref({});

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [];

    cols.push(
      {
        width: 60,
        slot: 'cash',
        label: '现结',
        align: 'center'
      },

      {
        width: 120,
        prop: 'cate',
        label: '类型'
      },
      {
        minWidth: 150,
        slot: 'insurance',
        label: '保险公司'
      },
      {
        minWidth: 150,
        slot: 'insurance_salesman',
        label: '业务员'
      },
      {
        width: 100,
        slot: 'rebate',
        label: '返点'
      },
      {
        width: 100,
        slot: 'totalPrice',
        label: '总价'
      },
      {
        width: 100,
        prop: 'price',
        label: '价格'
      },
      {
        width: 100,
        slot: 'otherPrice',
        label: '加价/车船'
      },
      {
        width: 230,
        slot: 's_time',
        label: '开始日期'
      },
      {
        width: 230,
        slot: 'e_time',
        label: '结束日期'
      },
      {
        width: 100,
        slot: 'img',
        label: '报价图片',
        align: 'center',
        fixed: 'right'
      },
      {
        label: '付款二维码',
        slot: 'payQrcode',
        width: 120,
        align: 'center',
        fixed: 'right'
      }
    );

    return cols;
  });

  /** 表格选中数据 */
  const selections = ref([]);

  /** 表格数据源 */
  var offerList = ref({});
  const datasource = async ({ page, limit, where, orders }) => {
    const result = await pageWatingBuyInsurance({
      ...where,
      ...orders,
      page,
      limit,
      trade_id: props.data.id,
      vehicle_id: props.data.vehicle_id,
      choose: 1
    });
    offerList.value = result.list;
    return result;
  };

  /** 搜索 */
  const reload = (where) => {
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 报价详情 */
  const offerId = ref(0);
  const showDetail = ref(false);

  /** 查看图片 */
  const imageType = ref('');
  const showImages = ref(false);
  const openImages = (data, type) => {
    imageType.value = type;
    current.value = data;
    showImages.value = true;
  };

  // 提交到付款
  const toPay = () => {
    ElMessageBox.confirm('提交到下一步？', '系统提示', {
      type: 'warning',
      draggable: true
    })
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        var requestData = {
          id: props.data.id,
          vehicle_id: props.data.vehicle_id,
          list: JSON.stringify(offerList.value)
        };
        setTradeToPay(requestData)
          .then(() => {
            loading.close();
            EleMessage.success('操作成功');
            emit('done');
          })
          .catch((e) => {
            loading.close();
            console.log(e);
          });
      })
      .catch(() => {});
  };

  /** 上传pdf完毕 */
  const onUpladDone = (e, row) => {
    console.log('上传成功', e, row);
    const requestData = {
      url: e,
      id: row.id
    };
    updateInsurancePdf(requestData)
      .then((res) => {
        console.log('更新成功', res);
        reload();
      })
      .catch(() => {});
  };
  const openPdf = (url) => {
    window.open(url);
  };

  /** 上传付款二维码完毕 */
  const onQrUpladDone = (e, row) => {
    console.log('上传成功', e, row);
    const requestData = {
      url: e,
      id: row.id
    };
    updateInsuranceOfferQr(requestData)
      .then((res) => {
        console.log('更新成功', res);
        reload();
      })
      .catch(() => {});
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };
  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        title.value = props.data.plate_number + '的出单要求';

        console.log(
          props.action,
          props.action == 'buy' || props.action == 'wating-confirm',
          '打开'
        );
      } else {
        console.log('关闭');
      }
    }
  );
</script>
